////////////////////////////////////////////////////////////////////////////////
// Copyright 2006 CORE Solutions Limited
// All rights reserved.
// PROPRIETARY AND CONFIDENTIAL INFORMATION.
// Use is subject to license terms.
//
// FUNCTION ID      :   SimpleMaintStyleActionTemplate.java
// AUTHOR           :   ric.yik
// DATE CREATE      :   2006/4/28
// DESCRIPTION      :
//                  :
//                  :
//                  :
//
// MODIFICATION HISTORY:
// DATE         AUTHOR          VERSION NO.         COMMENT
// -----------  --------------  ------------------  -------------------
// 2006/04/28   Ric Yik         1.0                 source is created.
// 2006/06/23   Ric Yik         1.0                 BugZilla #5535
//
////////////////////////////////////////////////////////////////////////////////

package com.erp.framework.controller.action;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.erp.app.common.ProjectConstants;
import com.erp.app.setup.taskMaster.beans.TaskDelegate;
import com.erp.app.setup.taskMaster.pk.TaskHdrPk;
import com.erp.app.util.web.WebUtil;
import com.erp.common.web.ActionMethodDispatcher;
import com.erp.common.web.PrefixActionMethodDispatcher;
import com.erp.framework.SimpleConstants;
import com.erp.framework.controller.form.MultiRow;
import com.erp.framework.controller.form.SimpleCoreForm;
import com.erp.framework.controller.form.SimpleMaintStyleForm;
import com.erp.framework.model.pk.SimpleBasePk;
import com.erp.framework.model.schema.MetaData;
import com.erp.framework.model.schema.TableSchema;
import com.erp.framework.util.BeanUtil;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;


public abstract class SimpleMaintStyleActionTemplate extends SimpleMaintStyleAction {

    protected ActionForward handlePageEvent(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {
        ActionForward actionForward = new ActionForward(mapping.getInput());
        if (this.isHandled(request)) {
            return actionForward;
        }
        try {
            SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
            actionForward = new ActionMethodDispatcher()
                .setAction(this)
                .setDefaultActionForward(actionForward)
                .setNextDispatcher(new PrefixActionMethodDispatcher()
                        .addPrefix(ProjectConstants.ACTION_SPEDIT)
                        .addPrefix(ProjectConstants.ACTION_DELETE_ROW)
                )
                .processAction(form.getPageEvent(), mapping, form, request, response, errors);
        } catch (Exception e) {
            Logger.logExceptions(this, e);
        }
        this.saveToken(request);
        this.setHandled(request);
        return actionForward;
    }

//    public void processActionSpEditAddHdrLabel(ActionMapping mapping, ActionForm formIn,
//            HttpServletRequest request, HttpServletResponse response, ActionErrors errors, LinkedList keyList) {
//
//    }

    public ActionForward processActionSpEdit(ActionMapping mapping, ActionForm formIn,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
        SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
        HttpSession session = request.getSession(false);
        ActionForward actionForward = new ActionForward(mapping.getInput());
        String action = CommonUtil.nullToString(form.getPageEvent());
        session.removeAttribute(ProjectConstants.SESSION_SELECT_REMARK_TEXT_PARAMETERS);
        String fieldName = BeanUtil.toPropertyName(form.getPageEvent().substring(ProjectConstants.ACTION_SPEDIT.length()));
        String fieldValue = "";
        String columnName = "";
        String eventSrc = form.getPageEventSrc();
        LinkedList keyList = new LinkedList();
//        processActionSpEditAddHdrLabel(mapping, form, request, response, errors, keyList);
        boolean readonly = form.isReadOnly();
        String fieldObjectId = "";
        Object formOrMultiRow = form;
        TableSchema ts = form.getTs();
        if (CommonUtil.isValidInteger(eventSrc)) {
            formOrMultiRow = WebUtil.getCurrentRow(form);
            readonly |= (((MultiRow) formOrMultiRow).isReadOnly() || ((MultiRow) formOrMultiRow).isDeleted());
            ts = form.getChildTs()[form.getCurrIdx()]; // MaintStyleForm-specific
        }
        MetaData metadata = ts.getMetaDataByVoName(fieldName);
        if (metadata == null) {
            metadata = BeanUtil.getMetaData(form, fieldName);
            if (metadata != null) fieldValue = CommonUtil.nullToString(BeanUtil.getPropertyDefault(form, fieldName));
        } else {
            fieldValue = CommonUtil.nullToString(BeanUtil.getPropertyDefault(formOrMultiRow, fieldName));
        }
        if (metadata == null) {
            Logger.debug(this, "metadata is null: " + fieldName);
            fieldValue = "metadata is null: " + fieldName;
        } else {
            fieldObjectId = metadata.getWebObjectId();
            columnName = metadata.getWebLabelName();
        }
        HashMap params = new HashMap();
        params.put(ProjectConstants.SESSION_SESSION_VALUE, getSessionSimpleMaintStatus());
        params.put(ProjectConstants.SESSION_OPENER_PATH, getFunctionId());
        params.put(ProjectConstants.SESSION_KEY_LIST, keyList);
        if (readonly) params.put(ProjectConstants.SESSION_SIMPLE_READ_ONLY, ProjectConstants.GENERIC_YES);
        params.put(ProjectConstants.SESSION_FIELD, fieldName);
        if (!CommonUtil.isEmpty(eventSrc)) params.put(ProjectConstants.SESSION_EVENTSRC, eventSrc);
        params.put(ProjectConstants.SESSION_EDIT_COLUMN_NAME, columnName);
        params.put(ProjectConstants.SESSION_EDIT_VALUE, fieldValue);
        params.put(ProjectConstants.SESSION_EDIT_COLUMN_OBJECT_ID, fieldObjectId);
        String useHtmlCode = CommonUtil.nullToString(session.getAttribute(ProjectConstants.SESSION_USE_HTML_CODE));
        session.removeAttribute(ProjectConstants.SESSION_USE_HTML_CODE);
        if(ProjectConstants.GENERIC_YES.equals(useHtmlCode)){
        	params.put(ProjectConstants.SESSION_USE_HTML_CODE, ProjectConstants.GENERIC_YES);
        }
        this.setValuesForActionSpEdit(mapping, formIn, request, response, errors, formOrMultiRow, ts, keyList, params);
        session.setAttribute(ProjectConstants.SESSION_SELECT_REMARK_TEXT_PARAMETERS, params);
        return actionForward;
    }

    protected void setValuesForActionSpEdit(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response,
    		ActionErrors errors, Object formOrMultiRow, TableSchema ts, LinkedList keyList, HashMap params) {
        params.put(ProjectConstants.SESSION_SIMPLE_HIDE_REMARK_MASTER, ProjectConstants.GENERIC_YES);
        params.put(ProjectConstants.SESSION_SIMPLE_HIDE_REMARK_DETAIL, ProjectConstants.GENERIC_YES);
        params.put(ProjectConstants.SESSION_SIMPLE_HIDE_REMARK_APPEND, ProjectConstants.GENERIC_YES);
    }

    protected ActionForward processOtherStatus(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors, String rb_status) {
        ActionForward actionForward = new ActionForward(mapping.getInput());
        try {
            SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
            actionForward = new ActionMethodDispatcher()
                .setAction(this)
                .setDefaultActionForward(actionForward)
                .setNextDispatcher(new PrefixActionMethodDispatcher().addPrefix(ProjectConstants.STATUS_SPSET))
                .setProcessStatus(true)
                .setStatus(rb_status)
                .processAction(form.getPageEvent(), mapping, form, request, response, errors);
        } catch (Exception e) {
            Logger.logExceptions(this, e);
        }
        this.saveToken(request);
        this.setHandled(request);
        return actionForward;
    }

    public ActionForward processStatusSPSet(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors, String rb_status) {
        SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
        HttpSession session = request.getSession(false);
        ActionForward actionForward = new ActionForward(mapping.getInput());
        HashMap params = (HashMap) session.getAttribute(ProjectConstants.SESSION_SELECT_REMARK_TEXT_PARAMETERS);
        session.removeAttribute(ProjectConstants.SESSION_SELECT_REMARK_TEXT_PARAMETERS);
        String editValue = (String) params.get(ProjectConstants.SESSION_EDIT_VALUE);
        String columnName = (String) params.get(ProjectConstants.SESSION_EDIT_COLUMN_NAME);
        String fieldObjectId = (String) params.get(ProjectConstants.SESSION_EDIT_COLUMN_OBJECT_ID);
        String fieldName = (String) params.get(ProjectConstants.SESSION_FIELD);
        String eventSrc = (String) params.get(ProjectConstants.SESSION_EVENTSRC);
        Object formOrMultiRow = form;
        TableSchema ts = form.getTs();
        if (CommonUtil.isValidInteger(eventSrc)) {
            formOrMultiRow = WebUtil.getCurrentRow(form);
            ts = form.getChildTs()[form.getCurrIdx()]; // MaintStyleForm-specific
        }
        BeanUtil.setPropertyDefault(formOrMultiRow, fieldName, editValue);
        return actionForward;
    }

    public ActionForward processActionDel(ActionMapping mapping, ActionForm formIn,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
        SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());
        WebUtil.delCurrentRow(form);
        return actionForward;
    }

    public ActionForward processActionChangeFolder(ActionMapping mapping, SimpleMaintStyleForm form, int tabIdx,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
        form.setPageEventSrc(String.valueOf(tabIdx + 1));
        return this.processActionChangeFolder(mapping, form, request, response, errors);
    }

    public List getTaskDetails(TaskHdrPk pk) {
        try {
            return new TaskDelegate().getTaskDetails(pk);
        } catch (Exception e) {
            Logger.logExceptions(this, e);
            return Collections.EMPTY_LIST;
        }
    }

    protected String getSimpleSrchMenuId(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response) {
        return this.getModuleName(mapping, formIn, request, response);
    }

    public void assignKey(SimpleCoreForm form, SimpleBasePk pk) {
        try {
            Map pkMap = BeanUtils.describe(pk);
            pkMap.remove("class");
            BeanUtils.populate(form, pkMap);

            if (form.getMultiRows() != null) {
                for (int i = 0; i < form.getMultiRows().size(); i++) {
                    List childList = form.getMultiRows(i);
                    if (childList != null) {
                        for (Iterator it = childList.iterator(); it.hasNext();) {
                            BeanUtils.populate(it.next(), pkMap);
                        }
                    }
                }
            }
        } catch (Exception e) {
            Logger.logExceptions(this, e);
        }
    }

    public ActionForward processActionGetAttachment(ActionMapping mapping, ActionForm formIn,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
        SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
        int currIdx = Integer.parseInt(request.getParameter("currIdx"));
        int idx = Integer.parseInt(request.getParameter("idx"));
        String imageProperty = request.getParameter("imageProperty");
        ArrayList rows = form.getMultiRows(currIdx);
        Object row = rows.get(idx);
        boolean download = SimpleConstants.GENERIC_YES.equals(request.getParameter("download"));
        if (row != null) {
            try {
                TableSchema ts = WebUtil.findTs(row, form, String.valueOf(currIdx));
                if (ts != null) {
                    MetaData md = ts.getMetaDataByVoName(imageProperty);
                    if (md != null) {
                        String contentType = (String) BeanUtil.getPropertyDefault(row, md.getContentTypeProperty());
                        String fileName = (String) BeanUtil.getPropertyDefault(row, md.getFileNameProperty());
                        String description = (String) BeanUtil.getPropertyDefault(row, md.getDescriptionProperty());
                        byte[] image = (byte[]) BeanUtil.getPropertyDefault(row, imageProperty);
                        response.setContentType(contentType);
                        response.setStatus(HttpServletResponse.SC_OK);
                        if (download) response.setHeader("Content-Disposition", "attachment;filename=\"" + CommonUtil.nullToString(fileName, description) + "\"");
                        OutputStream out = response.getOutputStream();
                        if (image != null) {
                            out.write(image);
                        }
                        out.close();
                    }
                }
            } catch (IOException e) {
                Logger.logExceptions(this, e);
            }
        }
        return null;
    }

    public ActionForward processActionDelAttach(ActionMapping mapping, ActionForm formIn,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
    	SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
    	ActionForward actionForward = new ActionForward(mapping.getInput());
        int currIdx = Integer.parseInt(request.getParameter("currIdx"));
        int idx = Integer.parseInt(request.getParameter("idx"));
        String imageProperty = request.getParameter("imageProperty");
        ArrayList rows = form.getMultiRows(currIdx);
        Object row = rows.get(idx);
        if (row != null) {
        	try{
        		TableSchema ts = WebUtil.findTs(row, form, String.valueOf(currIdx));
                if (ts != null) {
                	MetaData md = ts.getMetaDataByVoName(imageProperty);
                	if (md != null) {
                		BeanUtil.setPropertyDefault(row, md.getContentTypeProperty(), null);
                		BeanUtil.setPropertyDefault(row, imageProperty, null);
                        form.setRow(idx, row);
                	}
                }

            } catch (Exception e) {
                Logger.logExceptions(this, e);
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.error", e.getMessage()));
            }
        }
        return actionForward;
    }

    public ActionForward processActionAddAttach(ActionMapping mapping, ActionForm formIn,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
    	SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
    	ActionForward actionForward = new ActionForward(mapping.getInput());
    	HttpSession session = request.getSession(false);
        int currIdx = Integer.parseInt(request.getParameter("currIdx"));
        int idx = Integer.parseInt(request.getParameter("idx"));
        String imageProperty = request.getParameter("imageProperty");
        ArrayList rows = form.getMultiRows(currIdx);
        Object row = rows.get(idx);
        if (row != null) {
        	try{
        		TableSchema ts = WebUtil.findTs(row, form, String.valueOf(currIdx));
                if (ts != null) {
                	MetaData md = ts.getMetaDataByVoName(imageProperty);
                	 HashMap params = new HashMap();
                     LinkedList keyList = new LinkedList();
                     keyList.add(ts.getDisplayWebLabelByVoName(md.getIdentifier()));
                     keyList.add((String) BeanUtil.getPropertyDefault(row, md.getIdentifier()));
                     params.put(ProjectConstants.SESSION_KEY_LIST, keyList);
                     params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_NAME, getSessionSimpleMaintStatus());
                     params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_VALUE, ProjectConstants.STATUS_ADD_ATTACH);
                     params.put(ProjectConstants.SESSION_OPENER_PATH, getFunctionId());
                     session.setAttribute(ProjectConstants.SESSION_UPLOAD_FILE_PARAM, params);
                     session.setAttribute(ProjectConstants.SESSION_DOC_ATTACH_IDX, String.valueOf(idx));
                     session.setAttribute(ProjectConstants.SESSION_DOC_ATTACH_CURRENT_IDX, String.valueOf(currIdx));
                     session.setAttribute(ProjectConstants.SESSION_DOC_ATTACH_PROPERTY, imageProperty);
                }
        	} catch (Exception e) {
                Logger.logExceptions(this, e);
                errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.error", e.getMessage()));
            }
        }
        return actionForward;
    }

    public ActionForward processStatusAddAttach_set(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors, String rb_status) {
    	 SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
         HttpSession session = request.getSession(false);
         ActionForward actionForward = new ActionForward(mapping.getInput());
         try{
        	 FormFile file = form.getTemplate().getFormFile(mapping, formIn, request, response, errors);
        	 if (errors.size() > 0) {
                     saveErrors(request, errors);
                     saveToken(request);
                 } else {
                	 int currIdx = Integer.valueOf((String)session.getAttribute(ProjectConstants.SESSION_DOC_ATTACH_CURRENT_IDX)).intValue();
                     int idx = Integer.valueOf((String)session.getAttribute(ProjectConstants.SESSION_DOC_ATTACH_IDX)).intValue();
                     String imageProperty = (String)session.getAttribute(ProjectConstants.SESSION_DOC_ATTACH_PROPERTY);
                     session.removeAttribute(ProjectConstants.SESSION_DOC_ATTACH_CURRENT_IDX);
                     session.removeAttribute(ProjectConstants.SESSION_DOC_ATTACH_IDX);
                     session.removeAttribute(ProjectConstants.SESSION_DOC_ATTACH_PROPERTY);
                     ArrayList rows = form.getMultiRows(currIdx);
                     Object row = rows.get(idx);
                     TableSchema ts = WebUtil.findTs(row, form, String.valueOf(currIdx));
                     if (ts != null) {
                     	MetaData md = ts.getMetaDataByVoName(imageProperty);
                     	if (md != null) {
                     		String description = (String) BeanUtil.getPropertyDefault(row, md.getDescriptionProperty());
                     		BeanUtil.setPropertyDefault(row, md.getContentTypeProperty(), file.getContentType());
                     		BeanUtil.setPropertyDefault(row, imageProperty, file.getFileData());
                     		BeanUtil.setPropertyDefault(row, md.getFileNameProperty(), file.getFileName());
                     		BeanUtil.setPropertyDefault(row, md.getDescriptionProperty(), description);
                     		form.setCurrIdx(currIdx);
                            form.setRow(idx, row);
                     	}
                     }
                 }
         } catch (Exception e) {
             Logger.logExceptions(this, e);
             errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.error", e.getMessage()));
         }
         return actionForward;
    }

    public ActionForward processActionViewAttach(ActionMapping mapping, ActionForm formIn,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
    	SimpleMaintStyleForm form = (SimpleMaintStyleForm) formIn;
    	ActionForward actionForward = new ActionForward(mapping.getInput());
    	HttpSession session = request.getSession(false);
        int currIdx = Integer.parseInt(request.getParameter("currIdx"));
        int idx = Integer.parseInt(request.getParameter("idx"));
        String imageProperty = request.getParameter("imageProperty");
        ArrayList rows = form.getMultiRows(currIdx);
        Object row = rows.get(idx);
        try{
        	if (row != null) {
            	try{
            		TableSchema ts = WebUtil.findTs(row, form, String.valueOf(currIdx));
                    if (ts != null) {
                    	MetaData md = ts.getMetaDataByVoName(imageProperty);
                    	if (md != null) {
                    		String contentType = (String) BeanUtil.getPropertyDefault(row, md.getContentTypeProperty());
                    		byte[] image = (byte[]) BeanUtil.getPropertyDefault(row, imageProperty);
                            response.setContentType(contentType);
                            response.setStatus(HttpServletResponse.SC_OK);
                            OutputStream out = response.getOutputStream();
                            if (image != null) {
                                out.write(image);
                            }
                            out.close();
                    	}
                    }

                } catch (Exception e) {
                    Logger.logExceptions(this, e);
                    errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.error", e.getMessage()));
                }
            }
        }catch (Exception e) {
            Logger.logExceptions(this, e);
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.error", e.getMessage()));
        }
        return actionForward;
    }



}
